package com.scenic.afilechooser;

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.os.Environment;
import android.text.Editable;
import com.lenovo.nova.util.StringUtil;
import com.lenovo.nova.util.exec.JavaShellUtil;
import com.lenovo.nova.util.io.FileUtils;
import com.lenovo.nova.util.io.StreamUtil;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by scenic on 2015/3/25.
 */
public class ShellCmdLoader extends FileLoader {


    private Editable filter;
    public ShellCmdLoader(Context context, String path,Editable filter) {
        super(context, path);
        this.filter = filter;
    }

    @Override
    protected List<File> onLoadInBackground() {

        if(!StringUtil.isStringEmpty(filter)){
            JavaShellUtil shellUtil = new JavaShellUtil();
//            String cmd = "busybox find "+mPath + " | grep "+filter.toString();
            String cmd = "busybox find "+mPath + " -name '*."+filter.toString()+"'";
           final List<File> files = new ArrayList<File>();
            try {

                File file =new File(Environment.getExternalStorageDirectory(),"execute_find.txt");
                OutputStream outputStream= new FileOutputStream(file);
                shellUtil.executeLocalCmd(cmd,true,outputStream);
                outputStream.flush();
                outputStream.close();
                InputStream inputStream = new FileInputStream(file);
                StreamUtil.streamToString(inputStream, new StreamUtil.OnReadStreamHelper() {
                    @Override
                    public boolean isTerminal() {
                        return false;
                    }

                    @Override
                    public void onReaderLine(String line) {
                        files.add(new File(line));
                    }
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return files;
        }else {
            return super.onLoadInBackground();
        }




    }
}
